<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import { CreateElement } from 'vue'
import { fixedNumber } from '@/utils'

@Component({
  name: 'InputNumberWithRatioUnit'
})
export default class extends Vue {
  @Prop({ type: [String, Number] })
  private value!: string | number
  // conversion ratio
  @Prop({ type: Number, required: false, default: 1 })
  private ratio!: number
  // display precision
  @Prop({ type: Number, required: false, default: 9 })
  private precision!: number

  get precisionCorrection () {
    if (this.ratio >= 1) {
      return this.ratio.toString().split('.')[0].length - 1
    } else {
      return this.ratio.toString().split('.')[1].length * -1
    }
  }

  private formatInputNumber (v: string) {
    if (v) {
      this.$emit(
        'input',
        fixedNumber(
          Number(v) / this.ratio,
          this.precision + this.precisionCorrection
        )
      )
    }

    if (this.$listeners.hasOwnProperty('change')) {
      ;(this.$listeners.change as Function)(v)
    }
  }

  render (h: CreateElement) {
    return h(
      'el-input',
      {
        attrs: { step: 'any', ...this.$attrs },
        props: {
          ...this.$attrs,
          type: 'number',
          value:
            typeof this.value === 'number'
              ? fixedNumber(this.value * this.ratio, this.precision)
              : this.value
        },
        on: {
          ...this.$listeners,
          change: this.formatInputNumber,
          input: (v: string) => {
            this.$emit('input', v)
          }
        }
      },
      this.$attrs.innerSlot
        ? [
          h(
            'template',
            { slot: (this.$attrs.innerSlot as any).name },
            (this.$attrs.innerSlot as any).value
          )
        ]
        : null
    )
  }
}
</script>
